package com.bio.socket;

import sun.util.resources.cldr.so.CalendarData_so_KE;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;

/**
 * Created by fangjicai on 2020/6/4.
 */
public class SocketServer {

    public static void main(String[] args) throws IOException{
        ServerSocket serverSocket = new ServerSocket(8009);
        while (true) {
            Socket socket = serverSocket.accept();
            BufferedInputStream socketInputStream = new BufferedInputStream(socket.getInputStream());
            BufferedOutputStream socketOutputStream = new BufferedOutputStream(socket.getOutputStream());
            byte[] buff = new byte[8192];
            socketInputStream.read(buff);
            int fileLength = Integer.parseInt(new String(buff, 0, 15).trim());
            String fileNameLength = new String(buff, 15, 2).trim();
            String fileName = new String(buff, 17, Integer.parseInt(fileNameLength.trim()));
            System.out.println("开始接收文件。。。");
            System.out.println("文件名称：" + fileName);
            System.out.println("文件大小：" + fileLength + "字节");
            long startTimeMillis = System.currentTimeMillis();
            String newFileName = "recv_" + startTimeMillis + "_" + fileName;
            BufferedOutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(newFileName));
            int read = socketInputStream.read(buff, 0, buff.length);
            int readed = 0;
            //如果文件大小小于缓冲区的大小则输入流会一次性把所有数据读取出来
            //这时read会返回为-1，代码不会进入下面的while循环，所以需要提前判断一下
            if (read == -1 && fileLength > 0) {
                readed = fileLength;
                fileOutputStream.write(buff, 0, fileLength);
            }
            while (read != -1) {
                readed = readed + read;
                fileOutputStream.write(buff, 0, read);
                read = socketInputStream.read(buff, 0, buff.length);
            }
            fileOutputStream.flush();
            fileOutputStream.close();
            long endTimeMillis = System.currentTimeMillis();
            System.out.println("本次文件接收完毕，共用时：" + String.valueOf(endTimeMillis - startTimeMillis) + "毫秒");
            System.out.println("共写入文件字节数：" + readed);
            socket.shutdownOutput();
            socket.shutdownInput();
            socketInputStream.close();
            socketOutputStream.close();
            socket.close();
        }

    }

}
